/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.statementView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;

import com.ruipengkj.bean.TStore;
import com.ruipengkj.bean.ViewStoreStockSummary;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.exportExcel.StoreStockExportUtil;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonPrint;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RPJPanelStatementTop;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.model.statemnt.ViewStoreStockDetailModel;
import com.ruipengkj.model.statemnt.ViewStoreStockSummaryModel;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.service.ViewStoreStockSummaryService;
import com.ruipengkj.view.base.BasePagePanel;

/**
 * 说明：
 * 仓库库存报表
 * @Author：
 * @Date：2012-03-21
 */
public class StatementStore extends BasePagePanel<ViewStoreStockSummary> implements Runnable {
	private static final long serialVersionUID = 1L;
	private JLabelJComboBoxComponent store;//仓库
	private JButton queryButton;//查询
	
	private JButton exportButton; //导出
	
	private JTable table;//库存预警汇总表
	private ViewStoreStockSummaryModel ViewStoreStockSummaryModel;
	private JScrollPane tableJsp;//库存预警汇总表
	
//	private PagingComponent pagingComponent;//翻页组件
//	private PageView<ViewStoreStockSummary> pageView;//翻页主键
	
	private ViewStoreStockSummaryService ViewStoreStockSummaryService;//仓库
	private TStoreService tStoreService;
	
	public StatementStore() {
		tStoreService = BuildSpringApplication.getInstance().getTStoreServiceImpl();
		ViewStoreStockSummaryService = BuildSpringApplication.getInstance().getViewStoreStockSummaryServiceImpl();
		this.setLayout(new BorderLayout());
		this.init();
		this.initListener();
	}
	
	private void init() {
//		pageView=new PageView<ViewStoreStockSummary>();
		ViewStoreStockSummaryModel=new ViewStoreStockSummaryModel();
		table = uiFactory.createRPJTable(ViewStoreStockSummaryModel, null, this, 30, JLabel.CENTER);
		tableJsp = new JScrollPane(table);
		this.add(topPanel(),BorderLayout.NORTH);
		this.add(tableJsp);
		this.add(tailPanel(),BorderLayout.SOUTH);
		
		this.setOpaque(true);
		this.setBackground(new Color(247, 252, 255));
		table.setOpaque(false);
		tableJsp.setOpaque(false);
		tableJsp.getViewport().setOpaque(false); 
		this.add(uiFactory.createFlowJPanel(), BorderLayout.WEST);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.EAST);
		
		// 排序
		TableRowSorter<ViewStoreStockSummaryModel> tableRowSorter = new TableRowSorter<ViewStoreStockSummaryModel>(
				ViewStoreStockSummaryModel);
		table.setRowSorter(tableRowSorter);
		
		SwingUtilities.invokeLater(queryStore);
	}
	
	private JPanel topPanel() {
		JPanel jp1 = new RPJPanelStatementTop();
		store = new JLabelJComboBoxComponent("仓库：", new String[]{}, 188);
		store.addElement(new JComboBoxPOJO("请选择……"));
		queryButton= new RPJButtonBlue("查询");
		jp1.add(store);
		jp1.add(queryButton);
		return jp1;
	}
	
	private JPanel tailPanel() {
		JPanel tail_panel = uiFactory.createBorderJPanel();
		
		JPanel jp = uiFactory.createGridJPanel(1, 2);
		JPanel jp2 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		exportButton = new RPJButtonPrint("导 出");
		jp2.add(uiFactory.createJLabel("       "));
		jp2.add(exportButton);
		
		jp.add(jp2);
		
		tail_panel.add(jp);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.NORTH);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.SOUTH);
		return tail_panel;
	}
	
	private void initListener(){
		queryButton.addActionListener(this);
		exportButton.addActionListener(this);
	}
	
	private ViewStoreStockSummary queryTerm(){
		ViewStoreStockSummary ViewStoreStockSummary = new ViewStoreStockSummary();
		if (store.getBox().getSelectedIndex() != 0){
			JComboBoxPOJO po = (JComboBoxPOJO)store.getBox().getSelectedItem();
			ViewStoreStockSummary.setStoreName(po.getName());
		}
		return ViewStoreStockSummary;
	}
	
	//条件查询
	@Override
	protected void termQuery(int currentPage){
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
//					pageView.setCurrentPage(currentPage);
//					PageModel<ViewStoreStockSummary> pageModel = ViewStoreStockSummaryService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(),queryTerm());
//					pageView.setPageModel(pageModel);
//					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					List<ViewStoreStockSummary> StoreStockList = ViewStoreStockSummaryService.findService(queryTerm());
					if(StoreStockList!=null){
						TabelUtil.clearTableRowSorter(table);
						ViewStoreStockSummaryModel.setRowData(StoreStockList);
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								table.updateUI(); 
							}
						});
//						pagingComponent.show();
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						ViewStoreStockSummaryModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
//	@Override
//	protected PageView<ViewStoreStockSummary> getPageView() {
//		return pageView;
//	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==queryButton){
			//查询
			this.termQuery(0);
		}else if(e.getSource()==exportButton){
			//导出
			FileDialog fileDialog = new FileDialog(new JDialog(), "文件导出",FileDialog.SAVE);
			fileDialog.setVisible(true);
			String fileDir = fileDialog.getDirectory();
			String fileName = fileDialog.getFile();
			if (fileDir != null && !fileDir.equals("") && fileName != null&& !fileName.equals("")) {
				if (!fileName.toLowerCase().endsWith(".xls")) {
					if (fileName.lastIndexOf(".") != -1) {
						fileName = fileName.substring(0, fileName.lastIndexOf("."))+ ".xls";
					} else {
						fileName = fileName + ".xls";
					}
				}
				try {
					List<ViewStoreStockSummary> list = ViewStoreStockSummaryService.findExportService(this.queryTerm());
					if (list != null && list.size() != 0) {
						exportButton.setEnabled(false);
						StoreStockExportUtil.writeExcel(fileDir + fileName,list);
						JOptionPane.showMessageDialog(null, "导出成功");
					} else {
						JOptionPane.showMessageDialog(null, "数据为空，导出失败");
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "导出失败");
				}
				exportButton.setEnabled(true);
			}
		}
	}

	@Override
	public void run() {
		//查询
		this.termQuery(0);
	}
	
	//读取仓库数据
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList != null && tStoreList.size()!=0) {
					int length = tStoreList.size();
					for(int i = 0; i < length; ++i) {
						TStore tStore=tStoreList.get(i);
						store.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table && e.getClickCount() == 2) {
			new ViewStoreStockDetail(null, "仓库存量详细", true).showDialog((String)table.getValueAt(table.getSelectedRow(), 0));
		}
	}
	
	class ViewStoreStockDetail extends IDialog implements PageDelegale{
		private static final long serialVersionUID = 1L;
		
		private ViewStoreStockDetailModel ViewStoreStockDetailModel;
		private JScrollPane tableJsp;
		private JTable table;
		
		private PagingComponent pagingComponent;//翻页组件
		private PageView<ViewStoreStockSummary> pageView;//翻页主键
		
		private String storeName;//仓库名称
		
		public ViewStoreStockDetail(JDialog jd, String title, boolean b) {
			super(jd, title, b);
			this.setSize(900, 600);
			this.setResizable(false);
			this.setLocationRelativeTo(null);
			init();
		}
		
		private void init() {
			ViewStoreStockDetailModel = new ViewStoreStockDetailModel();
			table = uiFactory.createRPJTable(ViewStoreStockDetailModel, null, null, 30, JLabel.CENTER);
			tableJsp = new JScrollPane(table);
			
			pageView = new PageView<ViewStoreStockSummary>();
			pagingComponent = new PagingComponent();
			pagingComponent.setPageDelegale(this);
			
			tableJsp.setOpaque(false);
			tableJsp.getViewport().setOpaque(false);
			tableJsp.setBackground(Util.LIST_BACKGROUND);
			
			JPanel mainPanel = new BorderJPanel(new BorderLayout());
			mainPanel.add(tableJsp);
			mainPanel.add(pagingComponent, BorderLayout.SOUTH);
			mainPanel.setCursor(Util.CURSOR_DEFAULT);
			mainPanel.setBackground(Util.LIST_BACKGROUND);
			
			this.add(mainPanel);
		}
		
		protected Dimension getTitleSize() {
			return new Dimension(120, 29);
		}
		
		public void showDialog(String storeName) {
			this.storeName = storeName;
			termQuery(1);
			setVisible(true);
		}

		//条件查询
		private void termQuery(int currentPage){
			ViewStoreStockSummary viewStoreStockSummary = new ViewStoreStockSummary();
			viewStoreStockSummary.setStoreName(storeName);
			
			tableJsp.getViewport().remove(table);
			tableJsp.getViewport().add(waitComponent);
			try {
				pageView.setCurrentPage(currentPage);
				PageModel<ViewStoreStockSummary> pageModel=ViewStoreStockSummaryService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(), viewStoreStockSummary);
				pageView.setPageModel(pageModel);
				pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
				if(pageModel!=null){
					tableJsp.getViewport().remove(waitComponent);
					tableJsp.getViewport().add(table);
					ViewStoreStockDetailModel.setRowData(pageModel.getResultList());
					table.updateUI(); 
					pagingComponent.show();
				}else{
					//没有订单数据
					waitComponent.setText("不存在数据");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		/**--------------------------------翻页查询接口------------------------------------*/
		//首页
		@Override
		public void homePage() {
			this.termQuery(1);
		}
		//尾页
		@Override
		public void lastPage() {
			this.termQuery((int)pageView.getTotalPage());
		}
		//下一页
		@Override
		public void nextPage() {
			if(pageView.getCurrentPage()>=pageView.getTotalPage()){
				this.termQuery((int)pageView.getTotalPage());
			}else{
				this.termQuery(pageView.getCurrentPage()+1);
			}
		}
		//上一页
		@Override
		public void prevPage() {
			if(pageView.getCurrentPage()<=1){
				this.termQuery(1);
			}else{
				this.termQuery(pageView.getCurrentPage()-1);
			}
		}

		@Override
		public String getInfo() {
			return "当前第 "+pageView.getCurrentPage()+" 页/共 " +pageView.getTotalPage()+" 页";
		}
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}
}
